from mcp.server.fastmcp import FastMCP, Context
import subprocess
import json
from typing import Optional

mcp = FastMCP("CUPS MCP Server")

"""
面向软件：cups (Common UNIX Printing System)

MCP tools 列表：
1. cups_service_control - 控制 cups 服务（启动、停止、重启、重载）
   参数：action (str) - 操作类型：start/stop/restart/reload/status
   返回：统一 JSON 结构

2. cups_lpd_socket_control - 控制 cups-lpd.socket
   参数：action (str) - 操作类型：start/stop/status
   返回：统一 JSON 结构

3. cups_socket_control - 控制 cups.socket  
   参数：action (str) - 操作类型：start/stop/status
   返回：统一 JSON 结构
"""

@mcp.tool()
def cups_service_control(action: str) -> dict:
    """
    控制 cups 服务的启动、停止、重启、重载和状态查询
    
    参数:
        action: 操作类型，可选值: start/stop/restart/reload/status
    
    返回:
        {
            "success": bool,      # 操作是否成功
            "command": str,       # 执行的完整命令
            "exit_code": int,     # 命令退出码
            "stdout": str,        # 标准输出
            "stderr": str         # 标准错误
        }
    """
    valid_actions = ["start", "stop", "restart", "reload", "status"]
    if action not in valid_actions:
        return {
            "success": False,
            "command": f"systemctl {action} cups.service",
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Invalid action: {action}. Valid actions are: {', '.join(valid_actions)}"
        }
    
    command = ["systemctl", action, "cups.service"]
    try:
        result = subprocess.run(command, capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": " ".join(command),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(command),
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def cups_lpd_socket_control(action: str) -> dict:
    """
    控制 cups-lpd.socket 的启动、停止和状态查询
    
    参数:
        action: 操作类型，可选值: start/stop/status
    
    返回:
        {
            "success": bool,      # 操作是否成功
            "command": str,       # 执行的完整命令
            "exit_code": int,     # 命令退出码
            "stdout": str,        # 标准输出
            "stderr": str         # 标准错误
        }
    """
    valid_actions = ["start", "stop", "status"]
    if action not in valid_actions:
        return {
            "success": False,
            "command": f"systemctl {action} cups-lpd.socket",
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Invalid action: {action}. Valid actions are: {', '.join(valid_actions)}"
        }
    
    command = ["systemctl", action, "cups-lpd.socket"]
    try:
        result = subprocess.run(command, capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": " ".join(command),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(command),
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def cups_socket_control(action: str) -> dict:
    """
    控制 cups.socket 的启动、停止和状态查询
    
    参数:
        action: 操作类型，可选值: start/stop/status
    
    返回:
        {
            "success": bool,      # 操作是否成功
            "command": str,       # 执行的完整命令
            "exit_code": int,     # 命令退出码
            "stdout": str,        # 标准输出
            "stderr": str         # 标准错误
        }
    """
    valid_actions = ["start", "stop", "status"]
    if action not in valid_actions:
        return {
            "success": False,
            "command": f"systemctl {action} cups.socket",
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Invalid action: {action}. Valid actions are: {', '.join(valid_actions)}"
        }
    
    command = ["systemctl", action, "cups.socket"]
    try:
        result = subprocess.run(command, capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": " ".join(command),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(command),
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

if __name__ == "__main__":
    mcp.run()